package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.Feedback;
import com.mingqijia.gassafety.db.mapper.FeedbackMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.user.UserBackend;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.FeedbackRequest;
import com.mingqijia.gassafety.webserver.response.FeedBackAllResponse;
import com.mingqijia.gassafety.webserver.response.FeedbackResponse;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import com.mingqijia.gassafety.webserver.service.FeedbackService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author li.shiying
 * @since 2023-09-28
 */
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {

    @Autowired
    CompanyService companyService;

    @Override
    public PageUtil<FeedbackResponse> getFeedbackList(FeedbackRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        String userId = ApplicationUtils.getWorkingUser().getUsername();
        LambdaQueryWrapper<Feedback> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Feedback::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(request.getStatus() != null, Feedback::getStatus, request.getStatus())
                .like(request.getFeedbacker() != null, Feedback::getFeedbackAccount, request.getFeedbacker())
                .between(request.getStartDate() != null, Feedback::getCreatedAt, request.getStartDate(), request.getEndDate())
                .eq(!StringUtils.isEmpty(request.getSpId()), Feedback::getSpId, request.getSpId())
                .like(!"0".equals(spId), Feedback::getFeedbackAccount, "("+ userId + ")").orderByDesc(Feedback::getCreatedAt);

        Page<Feedback> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<Feedback> list = this.list(lqw);
        //企业名称
        List<FeedbackResponse> responseList = list.stream().map(item -> {
            FeedbackResponse response = new FeedbackResponse();
            BeanUtils.copyProperties(item, response);
            response.setSpName(companyService.getCompanyName(item.getSpId()));
            return response;
        }).collect(Collectors.toList());
        PageUtil<FeedbackResponse> pageUtil = new PageUtil<>(request.getPage(), request.getPageSize(), page.getTotal(), responseList);

        return pageUtil;
    }

    @Override
    public boolean add(FeedbackRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        Feedback feedback = new Feedback();
        feedback.setSpId(spId);
        feedback.setComment(request.getComment());
        String userId = ApplicationUtils.getWorkingUser().getUsername();
        String userName = ApplicationUtils.getWorkingUser().getName();
        feedback.setFeedbackAccount(userName + "(" + userId + ")");
        return this.save(feedback);
    }

    @Override
    public boolean reply(FeedbackRequest request) {
        if (request.getReply() == null){
            throw new BizException("意见回复不能为空！");
        }
        Feedback feedback = this.getById(request.getId());
        if (feedback == null){
            return false;
        }
        feedback.setStatus(1);
        feedback.setReply(request.getReply());
        feedback.setReplyTime(new DateTime());

        String userId = ApplicationUtils.getWorkingUser().getUsername();
        String userName = ApplicationUtils.getWorkingUser().getName();
        feedback.setReplyAccount(userName + "(" + userId + ")");
        //0-未查看 1-已查看
        feedback.setCheckStatus(0);

        return this.updateById(feedback);
    }

    @Override
    public boolean getCheckStatus() {

        String spId = ApplicationUtils.getWorkingSpId();
        String userId = ApplicationUtils.getWorkingUser().getUsername();
        String userName = ApplicationUtils.getWorkingUser().getName();
        LambdaQueryWrapper<Feedback> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Feedback::getSpId, spId).eq(Feedback::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Feedback::getFeedbackAccount, userName + "(" + userId + ")")
                .eq(Feedback::getCheckStatus, Constants.UNCHECKED);
        List<Feedback> list = this.list(lqw);
        return !CollectionUtils.isEmpty(list);

    }

    @Override
    public void editCheckStatus() {
        String spId = ApplicationUtils.getWorkingSpId();
        String userId = ApplicationUtils.getWorkingUser().getUsername();
        String userName = ApplicationUtils.getWorkingUser().getName();
        LambdaQueryWrapper<Feedback> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Feedback::getSpId, spId).eq(Feedback::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Feedback::getFeedbackAccount, userName + "(" + userId + ")")
                .eq(Feedback::getCheckStatus, Constants.UNCHECKED);
        List<Feedback> list = this.list(lqw);
        if (!CollectionUtils.isEmpty(list)){
            for (Feedback feedback : list) {
                feedback.setCheckStatus(Constants.CHECKED);
                this.updateById(feedback);
            }
        }
    }

    @Override
    public FeedBackAllResponse aggregation() {
        FeedBackAllResponse resp = new FeedBackAllResponse();
        resp.setUnReplyNumber(this.baseMapper.getNumber(Constants.APPEAL_STATUS_0));
        resp.setReplyNumber(this.baseMapper.getNumber(Constants.APPEAL_STATUS_1));
        resp.setTotal(this.baseMapper.getNumber(Constants.APPEAL_STATUS_1) + this.baseMapper.getNumber(Constants.APPEAL_STATUS_0));
        return resp;
    }
}
